package org.quadraspace.service.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quadraspace.filter.MethodReplacerFilter;
import org.quadraspace.model.Event;
import org.quadraspace.model.Mote;
import org.quadraspace.service.EventRepository;
import org.quadraspace.service.MoteRepository;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibernateMoteRepository extends HibernateDaoSupport implements MoteRepository, EventRepository {
	private static final String GET_MOTE_QUERY = "from Mote where id=?";
	private static Log logger = LogFactory.getLog(HibernateMoteRepository.class);
	public static final String GENERATED_PREFIX = "QUADRA_";
	private int generatedId = 0;

	@Override
	public boolean deleteMoteWithId(String moteId) {
		Mote toDel = (Mote) getMoteWithID(moteId);
		getHibernateTemplate().delete(toDel);
		return true;
	}

	@Override
	public String generateIdFor(Mote toAssignId) {
		return GENERATED_PREFIX + (generatedId++);
	}

	@Override
	public List<Mote> getAllMotes() {
		return getHibernateTemplate().loadAll(Mote.class);
	}

	@Override
	public Mote getMoteWithID(String id) {
		logger.trace("Retrieving mote with id ="+id);
		List<Mote> res = getHibernateTemplate().find(GET_MOTE_QUERY,id);
		if (res.size() > 0) {
			return (Mote) res.get(0);
		}
		return null;
	}

	@Override
	public void registerMote(Mote toSave) {
		getHibernateTemplate().saveOrUpdate(toSave);
	}

	@Override
	public void addEventForMoteWithID(String id, Event toAdd) {
		toAdd.setMoteId(id);
		getHibernateTemplate().saveOrUpdate(toAdd);
	}

	@Override
	public List<Event> getEventsForMoteWithId(String id) {
		List res = getHibernateTemplate().find("from org.quadraspace.model.Event as m where m.moteId ='" + id + "'");
		return res;
	}

	@Override
	public List<Event> getEventsForMoteWithId(String id, long startmillis, long endmillis) {
		List res = getHibernateTemplate().find("from org.quadraspace.model.Event as m where m.moteId ='" + id + "'" +
				" and m.timestamp >= "+startmillis+" and m.timestamp <= "+endmillis);
		return res;
	}

}
